﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace SynchronizedPlayer
{
    class FilesDB
    {
        public Dictionary<string, string> Files { get; private set; }
        readonly string[] supportedExtensions = { "mp3" };

        private bool inRange(string str, IEnumerable<string> range)
        {
            return range.Any(x => str.EndsWith(x));
        }
        Func<string, string> _hashBuilder;
        public FilesDB(string path, Func<string, string> hashBuilder)
        {
            _hashBuilder = hashBuilder;

            Files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
                .Where(x => inRange(x, supportedExtensions))
                .ToDictionary(hashBuilder);

        }
        public Tuple<int, double, IEnumerable<string>> FilterPlaylist(IEnumerable<string> badPlaylist, int current, double position)
        {
            int currentFinal = current;
            double positionFinal = position;

            var en = badPlaylist.GetEnumerator();
            en.MoveNext();
            List<string> files = new List<string>();
            foreach (string s in badPlaylist)
            {
                string hash = _hashBuilder(s);
                string value = null;
                if (Files.TryGetValue(hash, out value))
                {
                    files.Add(value); //one more path here
                }
                else
                {
                    currentFinal = (currentFinal > 0) ? (currentFinal - 1) : currentFinal;
                    positionFinal = 0.0;
                }

            }
            return new Tuple<int, double, IEnumerable<string>>(currentFinal, positionFinal, files);
        }
    }
}
